﻿using System;
using System.Collections.Generic;
using System.Web;
using System.Security.Cryptography;
using System.Text;
using System.Net.Mail;
using System.Net;
using System.Drawing;
using System.Drawing.Text;
using System.IO;
using System.Drawing.Imaging;
using System.Text.RegularExpressions;
using MDF.Utilites.Helper;

namespace MDF.Utilites.Tools
{
    /// <summary>
    /// Summary description for Utitys
    /// </summary>
     public class CommonMethods
    {
        private static String m_key = "123go";
        public static bool IsDebug = true;

        public static string rplc(string a)
        {
            a = a.Replace("\n", "<br/>");
            a = a.Replace("<", "&lt;");
            a = a.Replace(">", "&gt;");
            a = a.Replace("&lt;br/&gt;", "<br/>");
            return a;
        }

        public static string Md5Encode(string strEnc)
        {
            // Create a new instance of the MD5CryptoServiceProvider object.
            MD5 md5Hasher = MD5.Create();

            // Convert the input string to a byte array and compute the hash.
            byte[] data = md5Hasher.ComputeHash(Encoding.Default.GetBytes(strEnc));

            // Create a new Stringbuilder to collect the bytes
            // and create a string.
            StringBuilder sBuilder = new StringBuilder();

            // Loop through each byte of the hashed data 
            // and format each one as a hexadecimal string.
            for (int i = 0; i < data.Length; i++)
            {
                sBuilder.Append(data[i].ToString("x2"));
            }

            // Return the hexadecimal string.
            return sBuilder.ToString();
        }

        public static string Md5Decode(string strEnc)
        {
            byte[] keyArray = null;
            byte[] toEncryptArray = Convert.FromBase64String(strEnc);
            //byte[] toEncryptArray = UTF8Encoding.UTF8.GetBytes(toDecrypt);

            TripleDESCryptoServiceProvider tdes = new TripleDESCryptoServiceProvider();
            tdes.Key = keyArray;
            tdes.Mode = CipherMode.ECB;
            tdes.Padding = PaddingMode.PKCS7;

            ICryptoTransform cTransform = tdes.CreateDecryptor();
            byte[] resultArray = cTransform.TransformFinalBlock(toEncryptArray, 0, toEncryptArray.Length);

            return UTF8Encoding.Default.GetString(resultArray);
        }

        public static string Encrypt(string toEncrypt)
        {
            byte[] keyArray;
            byte[] toEncryptArray = UTF8Encoding.UTF8.GetBytes(toEncrypt);
            bool useHashing = true;
            if (useHashing)
            {
                MD5CryptoServiceProvider hashmd5 = new MD5CryptoServiceProvider();
                keyArray = hashmd5.ComputeHash(UTF8Encoding.UTF8.GetBytes(m_key));
            }
            else
                keyArray = UTF8Encoding.UTF8.GetBytes(m_key);

            TripleDESCryptoServiceProvider tdes = new TripleDESCryptoServiceProvider();
            tdes.Key = keyArray;
            tdes.Mode = CipherMode.ECB;
            tdes.Padding = PaddingMode.PKCS7;

            ICryptoTransform cTransform = tdes.CreateEncryptor();
            byte[] resultArray = cTransform.TransformFinalBlock(toEncryptArray, 0, toEncryptArray.Length);

            string strResult = Convert.ToBase64String(resultArray, 0, resultArray.Length);
            strResult = strResult.Replace("/", "___");
            return strResult;
        }

        public static string Decrypt(string toDecrypt)
        {
            toDecrypt = toDecrypt.Replace("___", "/");
            byte[] keyArray = null;
            byte[] toEncryptArray = Convert.FromBase64String(toDecrypt);
            //byte[] toEncryptArray = UTF8Encoding.UTF8.GetBytes(toDecrypt);
            bool useHashing = true;
            if (useHashing)
            {
                MD5CryptoServiceProvider hashmd5 = new MD5CryptoServiceProvider();
                keyArray = hashmd5.ComputeHash(UTF8Encoding.UTF8.GetBytes(m_key));
            }
            else
                keyArray = UTF8Encoding.UTF8.GetBytes(m_key);

            TripleDESCryptoServiceProvider tdes = new TripleDESCryptoServiceProvider();
            tdes.Key = keyArray;
            tdes.Mode = CipherMode.ECB;
            tdes.Padding = PaddingMode.PKCS7;

            ICryptoTransform cTransform = tdes.CreateDecryptor();
            byte[] resultArray = cTransform.TransformFinalBlock(toEncryptArray, 0, toEncryptArray.Length);

            return UTF8Encoding.UTF8.GetString(resultArray);
        }
        public static bool SendMail(string to, string subject, string body)
        {
            MailMessage message = new MailMessage();
            message.To.Add(to);
            message.Subject = subject;
            message.SubjectEncoding = System.Text.Encoding.UTF8;
            message.Body = body;
            message.BodyEncoding = System.Text.Encoding.UTF8;

            message.From = new MailAddress(MailConfig.From, MailConfig.DisplayName, System.Text.Encoding.UTF8);

            message.IsBodyHtml = true;
            message.Priority = MailPriority.High;
            NetworkCredential authentication = new NetworkCredential(MailConfig.MailUserName, MailConfig.MailPassWord);
            SmtpClient Mailclient = new SmtpClient(MailConfig.MailServer, 587);
            Mailclient.EnableSsl = true;

            Mailclient.UseDefaultCredentials = false;
            Mailclient.Credentials = authentication;
            try
            {
                Mailclient.Send(message);
            }
            catch
            {
                return false;
            }
            return true;
        }
        public static string RunScript(string _strScript)
        {
            _strScript = "<script language=\"javascript\">" + _strScript;
            _strScript += "</script>";
            return _strScript;
        }

        public static void Log(string _strTypeLog, string _strMessage)
        {
            if (!CommonMethods.IsDebug)
            {
                string strSQL = string.Format("insert into debug(type,message,date) values('{0}','{1}','{2}')", _strTypeLog, _strMessage, DateTime.Now);
                //GenericDataAccess.ExecuteNone(strSQL,DBConfig.DBStringConnection,DBConfig.DBProviderName);
            }
            else
            {
                throw new Exception(_strMessage);
            }

        }

        public static string CreateCaptCha(string pngString, string _strPath)
        {
            Random r = new Random();

            string pngName = CommonMethods.Md5Encode(DateTime.Now.ToString("yyMMddhhmmss") + pngString) + r.Next(1, 9999);

            // Set up Font
            Font pngFont = new Font("Raavi", 12);

            // Create a bitmap so we can create the Grapics object 
            Bitmap bm = new Bitmap(100, 23);
            Graphics gs = Graphics.FromImage(bm);

            // Measure string.
            SizeF pngSize = gs.MeasureString(pngString, pngFont);

            // Resize the bitmap so the width and height of the text 
            bm = new Bitmap(Convert.ToInt32(pngSize.Width), Convert.ToInt32(pngSize.Height));

            // Render the bitmap 
            gs = Graphics.FromImage(bm);
            gs.Clear(Color.White);
            gs.TextRenderingHint = TextRenderingHint.AntiAlias;
            gs.DrawString(pngString, pngFont, Brushes.Firebrick, 0, 0);
            gs.Flush();

            pngName += ".png";
            //Saving this as a PNG file
            FileStream myFileOut = new FileStream(_strPath + pngName, FileMode.Create);
            bm.Save(myFileOut, ImageFormat.Png);
            myFileOut.Close();
            try
            {
                DirectoryInfo diCurrentDir = new DirectoryInfo(_strPath);
                FileInfo[] fiTemp = diCurrentDir.GetFiles();

                for (int i = 0; i < fiTemp.Length; i++)
                {
                    DateTime flag = DateTime.Now.AddMinutes(-2);
                    int d = fiTemp[i].CreationTime.CompareTo(flag);
                    if (d == -1)
                    {
                        fiTemp[i].Delete();
                    }

                }
            }
            catch
            { }


            return pngName;

        }

        /*
     * A method to convert BBCode to HTML
     * Author: Danny Battison
     * Contact: gabehabe@googlemail.com
     */

        /// <summary>
        /// A method to convert basic BBCode to HTML
        /// </summary>
        /// <param name="str">A string formatted in BBCode</param>
        /// <returns>The HTML representation of the BBCode string</returns>
        public static string ConvertBBCodeToHTML(string str)
        {
            Regex exp;
            // format the bold tags: [b][/b]
            // becomes: <strong></strong>
            exp = new Regex(@"\[b\](.+?)\[/b\]");
            str = exp.Replace(str, "<strong>$1</strong>");

            // format the italic tags: [i][/i]
            // becomes: <em></em>
            exp = new Regex(@"\[i\](.+?)\[/i\]");
            str = exp.Replace(str, "<em>$1</em>");

            // format the underline tags: [u][/u]
            // becomes: <u></u>
            exp = new Regex(@"\[u\](.+?)\[/u\]");
            str = exp.Replace(str, "<u>$1</u>");

            // format the strike tags: [s][/s]
            // becomes: <strike></strike>
            exp = new Regex(@"\[s\](.+?)\[/s\]");
            str = exp.Replace(str, "<strike>$1</strike>");

            // format the url tags: [url=www.website.com]my site[/url]
            // becomes: <a href="www.website.com">my site</a>
            exp = new Regex(@"\[url\=([^\]]+)\]([^\]]+)\[/url\]");
            str = exp.Replace(str, "<a href=\"$1\">$2</a>");

            // format the img tags: [img]www.website.com/img/image.jpeg[/img]
            // becomes: <img src="www.website.com/img/image.jpeg" />
            exp = new Regex(@"\[img\]([^\]]+)\[/img\]");
            str = exp.Replace(str, "<img src=\"$1\" />");

            // format img tags with alt: [img=www.website.com/img/image.jpeg]this is the alt text[/img]
            // becomes: <img src="www.website.com/img/image.jpeg" alt="this is the alt text" />
            exp = new Regex(@"\[img\=([^\]]+)\]([^\]]+)\[/img\]");
            str = exp.Replace(str, "<img src=\"$1\" alt=\"$2\" />");

            //format the colour tags: [color=red][/color]
            // becomes: <font color="red"></font>
            // supports UK English and US English spelling of colour/color
            exp = new Regex(@"\[color\=([^\]]+)\]([^\]]+)\[/color\]");
            str = exp.Replace(str, "<font color=\"$1\">$2</font>");
            exp = new Regex(@"\[colour\=([^\]]+)\]([^\]]+)\[/colour\]");
            str = exp.Replace(str, "<font color=\"$1\">$2</font>");

            // format the size tags: [size=3][/size]
            // becomes: <font size="+3"></font>
            exp = new Regex(@"\[size\=([^\]]+)\]([^\]]+)\[/size\]");
            str = exp.Replace(str, "<font size=\"+$1\">$2</font>");

            // lastly, replace any new line characters with <br />
            str = str.Replace("\r\n", "<br />\r\n");

            return str;
        }

        public static string BBCode(string strTextToReplace)
        {

            ////Define regex 
            Regex regExp;

            ////Regex for URL tag without anchor 
            regExp = new Regex(@"\[url\]([^\]]+)\[\/url\]");
            strTextToReplace = regExp.Replace(strTextToReplace, "<a href=\"$1\">$1</a>");

            ////Regex for URL with anchor 
            regExp = new Regex(@"\[url=([^\]]+)\]([^\]]+)\[\/url\]");
            strTextToReplace = regExp.Replace(strTextToReplace, "<a href=\"$1\">$2</a>");

            ////Image regex 
            regExp = new Regex(@"\[img\]([^\]]+)\[\/img\]");
            strTextToReplace = regExp.Replace(strTextToReplace, "<img src=\"$1\" />");

            ////Bold text 
            regExp = new Regex(@"\[b\](.+?)\[\/b\]");
            strTextToReplace = regExp.Replace(strTextToReplace, "<b>$1</b>");

            ////Italic text 
            regExp = new Regex(@"\[i\](.+?)\[\/i\]");
            strTextToReplace = regExp.Replace(strTextToReplace, "<i>$1</i>");

            ////Underline text 
            regExp = new Regex(@"\[u\](.+?)\[\/u\]");
            strTextToReplace = regExp.Replace(strTextToReplace, "<u>$1</u>");

            ////Font size
            regExp = new Regex(@"\[size=([^\]]+)\]([^\]]+)\[\/size\]");
            strTextToReplace = regExp.Replace(strTextToReplace, "<span style=\"font-size: $1px\">$2</span>");

            ////Font color
            regExp = new Regex(@"\[color=([^\]]+)\]([^\]]+)\[\/color\]");
            strTextToReplace = regExp.Replace(strTextToReplace, "<span style=\"color: $1\">$2</span>");

            return strTextToReplace;
        }

        public static string HTML2BBCode(string desc)
        {
            desc = Regex.Replace(desc, @"<br(.*?) />", "[br]", RegexOptions.IgnoreCase);
            desc = Regex.Replace(desc, @"<UL[^>]*>", "[ulist]", RegexOptions.IgnoreCase);
            desc = Regex.Replace(desc, @"<\/UL>", "[/ulist]", RegexOptions.IgnoreCase);
            desc = Regex.Replace(desc, @"<OL[^>]*>", "[olist]", RegexOptions.IgnoreCase);
            desc = Regex.Replace(desc, @"<\/OL>", "[/olist]", RegexOptions.IgnoreCase);
            desc = Regex.Replace(desc, @"<LI>", "[*]", RegexOptions.IgnoreCase);
            desc = Regex.Replace(desc, @"<\/li>", "", RegexOptions.IgnoreCase);
            desc = Regex.Replace(desc, @"<B>", "[b]", RegexOptions.IgnoreCase);
            desc = Regex.Replace(desc, @"<\/B>>", "[/b]", RegexOptions.IgnoreCase);
            desc = Regex.Replace(desc, @"<STRONG>", "[strong]", RegexOptions.IgnoreCase);
            desc = Regex.Replace(desc, @"<\/STRONG>", "[/strong]", RegexOptions.IgnoreCase);
            desc = Regex.Replace(desc, @"<u>", "[u]", RegexOptions.IgnoreCase);
            desc = Regex.Replace(desc, @"<\/u>", "[/u]", RegexOptions.IgnoreCase);
            desc = Regex.Replace(desc, @"<i>", "[i]", RegexOptions.IgnoreCase);
            desc = Regex.Replace(desc, @"<\/i>", "[/i]", RegexOptions.IgnoreCase);
            desc = Regex.Replace(desc, @"<em>", "[em]", RegexOptions.IgnoreCase);
            desc = Regex.Replace(desc, @"<\/em>", "[/em]", RegexOptions.IgnoreCase);
            desc = Regex.Replace(desc, @"<sup>", "[sup]", RegexOptions.IgnoreCase);
            desc = Regex.Replace(desc, @"<\/sup>", "[/sup]", RegexOptions.IgnoreCase);
            desc = Regex.Replace(desc, @"<sub>", "[sub]", RegexOptions.IgnoreCase);
            desc = Regex.Replace(desc, @"<\/sub>", "[/sub]", RegexOptions.IgnoreCase);
            desc = Regex.Replace(desc, @"<HR[^>]*>", "[hr]", RegexOptions.IgnoreCase);
            desc = Regex.Replace(desc, @"<STRIKE>", "[strike]", RegexOptions.IgnoreCase);
            desc = Regex.Replace(desc, @"<\/STRIKE>", "[/strike]", RegexOptions.IgnoreCase);
            desc = Regex.Replace(desc, @"<h1>", "[h1]", RegexOptions.IgnoreCase);
            desc = Regex.Replace(desc, @"<\/h1>", "[/h1]", RegexOptions.IgnoreCase);
            desc = Regex.Replace(desc, @"<h2>", "[h2]", RegexOptions.IgnoreCase);
            desc = Regex.Replace(desc, @"<\/h2>", "[/h2]", RegexOptions.IgnoreCase);
            desc = Regex.Replace(desc, @"<h3>", "[h3]", RegexOptions.IgnoreCase);
            desc = Regex.Replace(desc, @"<\/h3>", "[/h3]", RegexOptions.IgnoreCase);
            desc = Regex.Replace(desc, @"<A HREF=", "[url=", RegexOptions.IgnoreCase);
            desc = Regex.Replace(desc, @"<\/A>", "[/url]", RegexOptions.IgnoreCase);
            desc = Regex.Replace(desc, @"'>", "']", RegexOptions.IgnoreCase);

            //match on image tags
            var match = Regex.Matches(desc, @"<IMG[\s\S]*?SRC=\'([\s\S]*?)\'[\s\S]*?>", RegexOptions.IgnoreCase);
            if (match.Count > 0)
                desc = Regex.Replace(desc, match[0].ToString(), "[img]" + match[0].Groups[1].Value + "[/img]", RegexOptions.IgnoreCase);

            return desc;
        }
        /// <summary>
        /// Hàm chuẩn hóa tên đối tượng khi đưa vào url
        /// </summary>
        /// <param name="_strName">Tên muốn dc chuẩn hóa</param>
        /// <returns>Chuổi đã chuẩn hóa</returns>
        public static string MakeUrlName(string _strName)
        {
            string strTemp = _strName;//.Replace(" ", "-").Replace("/", "-");
            strTemp = StringHelper.ToNonUnicodeAndLower(strTemp);
            return strTemp;
        }


    }
}